public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    //删除key的值
    public boolean remove(int key) {
        TreeNode cur = root;
        TreeNode curParent = root;
        //找到删除节点位置
        while(cur != null) {
            if(cur.key < key) {
                curParent = cur;
                cur = cur.right;
            }else if(cur.key > key) {
                curParent = cur;
                cur = cur.left;
            }else {
                break;
            }
        }
        if(cur == null) {
            return true;//节点不存在
        }
        TreeNode del = cur;//待删除节点
        TreeNode delParent = curParent;//待删除节点的父亲节点
        //找到待删除节点左子树的最大值（即左子树最右边的元素），用来替换法1待删除节点值
        if(del.left == null) {//待删除节点无左子树
            if(del.key > delParent.key) {
                delParent.right = del.right;
            }else if(del.key < delParent.key){
                delParent.left = del.right;
            }else {
                //此时，待删除节点为根节点
                root = root.right;
            }
        }else {
            //找到待删除节点左子树的最大值（即左子树最右边的元素），用来替换待删除节点值
            curParent = cur;
            cur = cur.left;
            while(cur.right != null) {
                curParent = cur;
                cur = cur.right;
            }
            del.key = cur.key;
            if(curParent == del) {
                //此时，待删除节点的左子树根节点无右子树
                curParent.left = cur.left;
            }else {
                curParent.right = cur.left;
            }
        }
        return true;
    }

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        if(root == null) {
            root = new TreeNode(key);
            return true;
        }
        TreeNode node = new TreeNode(key);
        TreeNode cur = root;
        TreeNode curParent = null;
        //找插入新节点的合适位置
        while(cur != null) {
            curParent = cur;
            if(cur.key < key) {
                cur = cur.right;
            }else if(cur.key > key) {
                cur = cur.left;
            }else {
                return false;
            }
        }
        //进行插入新节点操作
        if(curParent.key < key) {
            curParent.right = node;
        }else {
            curParent.left = node;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur = root;
        while(cur != null) {
            if(cur.key < key) {
                cur = cur.right;
            }else if(cur.key > key) {
                cur = cur.left;
            }else {
                return cur;
            }
        }
        return null;
    }

}